package midway.madness;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import midway.madness.post.PostObject;
import midway.madness.post.article.ArticlesListAdapter;
import midway.madness.utils.ApplicationEx;
import midway.madness.utils.SplashScreen;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;

public class CategoryActivity extends Activity {

	private SplashScreen splash;
	private List<PostObject> categoriesList = new ArrayList<PostObject>();
	private CategoryObject catObj;
	private Handler handler;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		splash = new SplashScreen(this);
		splash.showSplash();

		setContentView(R.layout.main_menu);

		Intent pastIntent = this.getIntent();
		catObj = new CategoryObject(pastIntent.getIntExtra("catId", 0),
				pastIntent.getIntExtra("catParId", 0),
				pastIntent.getStringExtra("catName"),
				pastIntent.getStringExtra("catSlug"));

		handler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch (msg.what) {
				case ApplicationEx.HANDLE_ERR:
					ApplicationEx appEx = (ApplicationEx) getApplication();
					AlertDialog alert = appEx.handleError(
							CategoryActivity.this,
							msg.getData().getString("errorMsg"));
					alert.setOnDismissListener(new OnDismissListener() {

						public void onDismiss(DialogInterface dialog) {
							CategoryActivity.this.finish();
						}
					});
					splash.removeSplash();
					alert.show();
					break;
				default:
					super.handleMessage(msg);
					break;
				}
			}

		};

		new DownloadCategories().execute(new Void[0]);
	}

	private class DownloadCategories extends AsyncTask<Void, Void, Void> {

		@Override
		protected Void doInBackground(Void... params) {
			JSONObject obj;
			JSONArray posts = null;
			try {
				obj = ((ApplicationEx) getApplication())
						.postJson(
								"http://midwaymadness.com/api/get_category_posts/?dev=1",
								new String[] { "slug" },
								new String[] { catObj.getSlug() });
				if (!obj.getString("status").equals("ok")) {
					Bundle data = new Bundle();
					data.putString("errorMsg",
							((ApplicationEx) getApplication()).getMessage(obj
									.getString("status")));
					Message msg = new Message();
					msg.setData(data);
					msg.what = ApplicationEx.HANDLE_ERR;
					handler.sendMessage(msg);
					return null;
				} else {
					posts = obj.getJSONArray("posts");
					for (int i = 0; i < posts.length(); i++) {
						JSONObject post;
						post = posts.getJSONObject(i);
						PostObject temp;
						try {
							temp = ((ApplicationEx) getApplication())
									.whatAmI(post);
							if (null != temp) {
								categoriesList.add(temp);
							}
						} catch (IOException e) {
							Bundle data = new Bundle();
							data.putString("errorMsg",
									((ApplicationEx) getApplication())
											.getMessage("reader"));
							Message msg = new Message();
							msg.setData(data);
							msg.what = ApplicationEx.HANDLE_ERR;
							handler.sendMessage(msg);
						}
					}
				}
			} catch (JSONException e1) {
				Bundle data = new Bundle();
				data.putString("errorMsg",
						((ApplicationEx) getApplication()).getMessage("reader"));
				Message msg = new Message();
				msg.setData(data);
				msg.what = ApplicationEx.HANDLE_ERR;
				handler.sendMessage(msg);
				return null;
			}
			return null;
		}

		protected void onPostExecute(Void v) {
			final ListView listView = (ListView) findViewById(R.id.main_list_view);
			listView.setAdapter(new ArticlesListAdapter(CategoryActivity.this,
					android.R.layout.simple_list_item_1, categoriesList));
			listView.setTextFilterEnabled(true);
			listView.setOnItemClickListener(new OnItemClickListener() {

				public void onItemClick(AdapterView<?> adapterView, View view,
						int pos, long id) {
					PostObject obj = categoriesList.get(pos);
					obj.goForIntent();
				}

			});
			listView.setCacheColorHint(0x16FFFF);
			splash.removeSplash();
			if (categoriesList.isEmpty()) {
				AlertDialog.Builder builder = new Builder(CategoryActivity.this);
				builder.setNeutralButton("Okay.", new OnClickListener() {

					public void onClick(DialogInterface dialog, int which) {
						CategoryActivity.this.finish();
					}
				});
				builder.setMessage(getResources()
						.getString(R.string.post_error));
				builder.show();
			}
		}

	}

	public void doSearch(View view) {
		String searchText = ((EditText) findViewById(R.id.search_txt))
				.getText().toString().trim();
		if (searchText.equals("")) {
			return;
		}
		Intent intent = new Intent(CategoryActivity.this, SearchActivity.class);
		intent.putExtra("searchText", searchText);
		startActivity(intent);
	}
}
